#!/bin/bash

# Usage:
#	_d_config_get_sections <config_file>
#
# Description:
#	Returns the name of each section in an ini formatted configuration file
# 
# Notes:
#	# config file format
#	[section]
#		foo="a b c"
#		bar=1
#
_d_config_get_sections() {
   typeset config_file=$1
   awk -F '[][]' 'NF==3 && $0 ~ /^\[.*\]/ { print $2 }' ${config_file} | egrep -v '^#'
}

# Usage:
#	_d_config_set_vars <config_file> <section> [var_prefix]
#
# Description:
#	Set variables (optionaly prefixed by [var_prefix]) from <section> in <config_file>
#
# Notes:
#	None.
#
_d_config_set_vars() {
   typeset config_file=$1
   typeset config=$2
   typeset var_prefix=$3
   typeset config_vars

   config_vars=$( 
        awk -F= -v Config="${config}" -v Prefix="${var_prefix}" '
        BEGIN { 
           Config = toupper(Config);
           patternConfig = "\\[" Config "]";
        }
        toupper($0)  ~ patternConfig,(/\[/ && toupper($0) !~ patternConfig)  { 
           if (/\[/ || NF <2) next;
           sub(/^[[:space:]]*/, "");
           sub(/[[:space:]]*=[[:space:]]/, "=");
           print "export " Prefix $0;
        } ' ${config_file} | grep -v "${var_prefix}#")

   eval "${config_vars}"
}

_d_config_load() {
	_d_module_config_path=$1
	for conf in ${_d_module_config_path}/*.conf
	do
		module=$(basename ${conf} | awk -F '.conf$' '{print $1}')
		sections=$(_d_config_get_sections "${conf}")
		for section in ${sections}
		do
			_d_config_set_vars "${conf}" "${section}" "${module}_${section}_"
		done
	done

	return 0
}

_d_config_search_keys() {
	varstring=$1
	env | egrep "${varstring}"
	return $?
}

